﻿using Google.Protobuf.WellKnownTypes;
using MySql.Data.MySqlClient;
using MySql.Data.MySqlClient.Memcached;
using Org.BouncyCastle.Asn1.Crmf;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Management;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;
using System.Data.SQLite;
using Ubiety.Dns.Core;
using log4net.Util;
using static log4net.Appender.RollingFileAppender;
using CloudApiServer.Class;
using System.Security.Cryptography;
using NPOI.HPSF;
using NPOI.Util;

namespace CloudApiServer
{
    /// <summary>
    /// 公共方法
    /// </summary>
    public class PublicMethod
    {
        /// <summary>
        /// 计算年龄
        /// </summary>
        /// <param name="birthDate">生日</param>
        /// <param name="currentDate">当前日期</param>
        /// <returns>年龄</returns>
        public static int CalculateAge(DateTime birthDate, DateTime currentDate)
        {
            // 如果当前日期小于出生日期，则返回0，表示年龄不合法  
            if (currentDate < birthDate)
            {
                return 0;
            }
            // 计算年份差  
            int years = currentDate.Year - birthDate.Year;
            // 如果当前月份和日期小于出生日期，说明今年还没过生日，年龄减1  
            if (currentDate.Month < birthDate.Month ||
                (currentDate.Month == birthDate.Month && currentDate.Day < birthDate.Day))
            {
                years--;
            }
            return years;
        }


        public static readonly char[] chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".ToCharArray();

        /// <summary>
        /// 生成随机字符串
        /// </summary>
        /// <param name="length"></param>
        /// <returns></returns>
        public static string GenerateRandomString(int length)
        {
            var stringBuilder = new StringBuilder(length);
            var random = new Random();

            for (int i = 0; i < length; i++)
            {
                stringBuilder.Append(chars[random.Next(chars.Length)]);
            }

            return stringBuilder.ToString();
        }

        /// <summary>
        /// 通用API请求方法
        /// </summary>
        /// <param name="state">返回状态</param>
        /// <param name="url">请求地址</param>
        /// <param name="Json">请求入参</param>
        /// <returns>接口返回 </returns>
        public static string ApiPost(out bool state, string url,string Json)
        {
            try
            {
                Console.WriteLine($"内部服务调用地址：{url};入参：{Json}");
                if (FsiDatainfo.stateLocalApiInInternal == false)
                {
                    throw new Exception($"内部服务调用已被控制台停用，请联系管理员确认控制台是否停用！内部服务调用地址:{url} 调用入参:{Json}");
                }
                var client = new RestClient(baseUrl: url);
                var request = new RestRequest("", RestSharp.Method.Post);
                request.AddParameter("application/json", Json, ParameterType.RequestBody);
                var response = client.Execute(request);
                int statusCode = (int)response.StatusCode;
                if (statusCode == 0)
                {
                    state = false;
                    return $"请求状态码异常，{url}无法访问或服务异常";
                }
                else if (statusCode != 200)
                {
                    state = false;
                    return $"请求状态码：{statusCode},异常返回:{response.Content}";
                }
                else
                {
                    state=true;
                    return response.Content;
                }
            }
            catch (Exception e)
            {
                state = false;
                return $"服务内部异常：{e.Message} 异常来源：{e.StackTrace}";
            }
        }

        /// <summary>
        /// 通用API请求方法
        /// </summary>
        /// <param name="state">返回状态</param>
        /// <param name="url">请求地址</param>
        /// <returns>接口返回 </returns>
        public static string ApiGet(out bool state, string url)
        {
            try
            {
                Console.WriteLine($"内部服务调用地址：{url}");
                if (FsiDatainfo.stateLocalApiInInternal == false)
                {
                    throw new Exception($"内部服务调用已被控制台停用，请联系管理员确认控制台是否停用！内部服务调用地址:{url}");
                }
                var client = new RestClient(baseUrl: url);
                var request = new RestRequest("", RestSharp.Method.Get);
                var response = client.Execute(request);
                int statusCode = (int)response.StatusCode;
                if (statusCode == 0)
                {
                    state = false;
                    return $"请求状态码异常，{url}无法访问或服务异常";
                }
                else if (statusCode != 200)
                {
                    state = false;
                    return $"请求状态码：{statusCode},异常返回:{response.Content}";
                }
                else
                {
                    state = true;
                    return response.Content;
                }
            }
            catch (Exception e)
            {
                state = false;
                return $"服务内部异常：{e.Message} 异常来源：{e.StackTrace}";
            }
        }

        public static string ComputeMD5(string input)
        {
            using (MD5 md5 = MD5.Create())
            {
                // 将输入字符串转换为字节数组
                byte[] inputBytes = Encoding.UTF8.GetBytes(input);
                // 计算哈希值
                byte[] hashBytes = md5.ComputeHash(inputBytes);
                // 将字节数组转换为16进制字符串
                StringBuilder sb = new StringBuilder();
                foreach (byte b in hashBytes)
                {
                    sb.Append(b.ToString("x2")); // x2表示以小写16进制格式输出
                }
                return sb.ToString();
            }
        }

        /// <summary>
        /// 签到信息校验方法
        /// </summary>
        /// <param name="fixmedinscode">机构代码</param>
        /// <param name="opter_no">操作员编号</param>
        /// <param name="signno">签到值</param>
        /// <returns>是否已签到</returns>
        /// <exception cref="Exception"></exception>
        public static async Task<bool> FsisignIn(string fixmedinscode, string opter_no, string signno)
        {
            string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                try
                {
                    await conn.OpenAsync();
                    using (MySqlCommand cmd = conn.CreateCommand())
                    {
                        cmd.CommandText = "select * from fsi_signinout where fixmedins_code=@fixmedins_code and opter_no=@opter_no and sign_no= @sign_no and state=0 ";
                        cmd.Parameters.AddWithValue("@fixmedins_code", fixmedinscode);
                        cmd.Parameters.AddWithValue("@opter_no", opter_no);
                        cmd.Parameters.AddWithValue("@sign_no", signno);
                        using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync())
                        {
                            DataTable dt = new DataTable();
                            dt.Load(reader);
                            if (dt.Rows.Count < 1)
                            {
                                return false;
                            }
                            else
                            {
                                return true;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception($"校验签到信息失败：调用签到记录查询方法失败！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        await conn.CloseAsync();
                    }
                }
            }
        }

        /// <summary>
        /// 验证接口密码
        /// </summary>
        /// <param name="ApiUrlName">接口名称</param>
        /// <param name="password">密码</param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public static async Task<bool> ApiPasswordAuth(string ApiUrlName, string password)
        {
            string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                try
                {
                    await conn.OpenAsync();
                    using (MySqlCommand cmd = conn.CreateCommand())
                    {
                        cmd.CommandText = "select * from apipassword where ApiUrlName=@ApiUrlName and password=@password";
                        cmd.Parameters.AddWithValue("@ApiUrlName", ApiUrlName);
                        cmd.Parameters.AddWithValue("@password", password);
                        using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync())
                        {
                            DataTable dt = new DataTable();
                            dt.Load(reader);
                            if (dt.Rows.Count < 1)
                            {
                                return false;
                            }
                            else
                            {
                                return true;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception($"校验接口密钥失败：调用接口密钥记录查询方法失败！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        await conn.CloseAsync();
                    }
                }
            }
        }

        /// <summary>
        /// 结算后插入人员费用明细
        /// </summary>
        /// <param name="mdtrtId">单据号</param>
        /// <param name="feeOcurTime">费用日期</param>
        /// <param name="hiListCode">项目编码</param>
        /// <param name="hiListName">项目名称</param>
        /// <param name="cnt">数量</param>
        /// <param name="psnno">人员编号</param>
        /// <param name="psnname">人员姓名</param>
        /// <param name="fixmedins_code">机构代码</param>
        /// <param name="fixmedins_name">机构名称</param>
        /// <returns>结算后插入人员费用明细</returns>
        /// <exception cref="Exception"></exception>
        public static async Task<bool> FsiInsertquerydrugdosag(List<FsiQuerydrugdosagInsert> querydrugdosagInsertList)
        {
            string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                try
                {
                    DateTime dateTime = DateTime.Now;
                    await conn.OpenAsync();
                    string error = "";
                    using (MySqlTransaction transaction = conn.BeginTransaction())
                    {
                        using (MySqlCommand cmd = conn.CreateCommand())
                        {
                            cmd.Transaction = transaction;

                            foreach (var item in querydrugdosagInsertList)
                            {
                                try
                                {
                                    string listType;
                                    string medChrgitmType;
                                    if (item.hilistCode.StartsWith("X"))
                                    {
                                        listType = "101";
                                        medChrgitmType = "09";
                                    }
                                    else if ( item.hilistCode.StartsWith("Z"))
                                    {
                                        listType = "101";
                                        medChrgitmType = "11";
                                    }
                                    else if (item.hilistCode.StartsWith("T"))
                                    {
                                        listType = "102";
                                        medChrgitmType = "10";
                                    }
                                    else if (item.hilistCode.StartsWith("Q02")|| item.hilistCode.StartsWith("C"))
                                    {
                                        listType = "301";
                                        medChrgitmType = "08";
                                    }
                                    else
                                    {
                                        listType = "";
                                        medChrgitmType = "14";
                                    }

                                    cmd.CommandText = "INSERT INTO `data`.`fsi_querydrugdosag` ( `mdtrtId`, `feeOcurTime`, `hiListCode`, `cnt`, `sinDosDscr`, `usedFrquDscr`, `psnno`, `fixmedins_code`, `fixmedins_name`, `create_time`, `update_time`," +
                                        " `listType`, `medinsListCodg`, `medinsListName`, `medChrgitmType`, `chrgitmLv`, `pric`, `detItemFeeSumamt`, `inscpAmt`, `bilgDrCode`, `bilgDrName`, `ds`) " +
                                        " VALUES ( @mdtrtId, @feeOcurTime, @hiListCode,@cnt,@sinDosDscr,@usedFrquDscr,@psnno,@fixmedins_code, @fixmedins_name, @create_time, @update_time," +
                                        " @listType, @medinsListCodg, @medinsListName, @medChrgitmType, @chrgitmLv, @pric, @detItemFeeSumamt, @inscpAmt, @bilgDrCode, @bilgDrName, @ds);";
                                    cmd.Parameters.AddWithValue("@mdtrtId", item.mdtrtId);
                                    cmd.Parameters.AddWithValue("@feeOcurTime", item.feeOcurTime);
                                    cmd.Parameters.AddWithValue("@hiListCode", item.hilistCode);
                                    cmd.Parameters.AddWithValue("@sinDosDscr", item.sinDosDscr);
                                    cmd.Parameters.AddWithValue("@cnt", item.cnt);
                                    cmd.Parameters.AddWithValue("@psnno", item.psnno);
                                    cmd.Parameters.AddWithValue("@usedFrquDscr", item.usedFrquDscr);
                                    cmd.Parameters.AddWithValue("@fixmedins_code", item.fixmedins_code);
                                    cmd.Parameters.AddWithValue("@fixmedins_name", item.fixmedins_name);
                                    cmd.Parameters.AddWithValue("@create_time", dateTime.ToString("yyyy-MM-dd HH-mm-ss"));
                                    cmd.Parameters.AddWithValue("@update_time", dateTime.ToString("yyyy-MM-dd HH-mm-ss"));
                                    cmd.Parameters.AddWithValue("@listType", listType);
                                    cmd.Parameters.AddWithValue("@medinsListCodg", item.medinsListCodg);
                                    cmd.Parameters.AddWithValue("@medinsListName", item.medinsListName);
                                    cmd.Parameters.AddWithValue("@medChrgitmType", medChrgitmType);
                                    cmd.Parameters.AddWithValue("@chrgitmLv", item.chrgitmLv);
                                    cmd.Parameters.AddWithValue("@pric", item.pric);
                                    cmd.Parameters.AddWithValue("@detItemFeeSumamt", item.detItemFeeSumamt);
                                    cmd.Parameters.AddWithValue("@inscpAmt", item.inscpAmt);
                                    cmd.Parameters.AddWithValue("@bilgDrCode", item.bilgDrCode);
                                    cmd.Parameters.AddWithValue("@bilgDrName", item.bilgDrName);
                                    cmd.Parameters.AddWithValue("@ds", item.ds);

                                    await cmd.ExecuteNonQueryAsync();
                                    cmd.Parameters.Clear();
                                }
                                catch (Exception ex)
                                {
                                    error = error + $" 【{item.hilistCode}】历史费用明细记录表插入失败：" + ex.Message + "|";
                                }
                                cmd.Parameters.Clear();
                            }
                            if (error != "")
                            {
                                transaction.Rollback();
                                throw new Exception(error);
                            }
                            else
                            {
                                transaction.Commit();
                                return true;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    throw new($"历史费用明细记录表插入失败：费用明细记录表插入失败！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        await conn.CloseAsync();
                    }
                }
            }
        }
        /// <summary>
        /// 获取医保字典值
        /// </summary>
        /// <param name="codevalue">字典代码</param>
        /// <param name="categorydesc">字典类型</param>
        /// <returns>字典中文</returns>
        /// <exception cref="Exception"></exception>
        public static async Task<string>  GetMedicareDict(string codevalue, string category)
        {
            string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                try
                {
                    await conn.OpenAsync();
                    using (MySqlCommand cmd = conn.CreateCommand())
                    {
                        cmd.CommandText = "select * from medicare_dict where NAT_DIC_VAL_CODE=@category and DIC_TYPE_CODE=@code_value ";
                        cmd.Parameters.AddWithValue("@code_value", codevalue);
                        cmd.Parameters.AddWithValue("@category", category);
                        using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync())
                        {
                            DataTable dt = new DataTable();
                            dt.Load(reader);
                            if (dt.Rows.Count == 1)
                            {
                                return dt.Rows[0]["NAT_DIC_VAL_NAME"].ToString();
                            }
                            else
                            {
                                throw new Exception($"医保字典取值失败：调用医保字典取值方法失败！查询到了{dt.Rows.Count}条字典类型为{category},字典代码值为{codevalue}");
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception($"医保字典取值失败：调用医保字典取值方法失败！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        await conn.CloseAsync();
                    }
                }
            }

        }
        /// <summary>
        /// 获取医保区域规划
        /// </summary>
        /// <param name="admdvs"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public static async Task<string> GetMedicareDivision(string admdvs)
        {
            string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                try
                {
                    await conn.OpenAsync();
                    using (MySqlCommand cmd = conn.CreateCommand())
                    {
                        cmd.CommandText = "select * from medicare_division where admdvs=@admdvs";
                        cmd.Parameters.AddWithValue("@admdvs", admdvs);
                        using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync())
                        {
                            DataTable dt = new DataTable();
                            dt.Load(reader);
                            if (dt.Rows.Count == 1)
                            {
                                return dt.Rows[0]["admdvs_name"].ToString();
                            }
                            else
                            {
                                throw new Exception($"医保参保区划名称取值失败：调用医保参保区划名称方法失败！查询到了{dt.Rows.Count}条区划代码为{admdvs}的值!");
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception($"医保参保区划名称取值失败：调用医保参保区划名称方法失败！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        await conn.CloseAsync();
                    }
                }
            }

        }
        /// <summary>
        ///山东地纬xml格式输出
        /// </summary>
        /// <param name="Json">出参Json</param>
        /// <returns>出参</returns>
        public static string DarewayOutputXML(string Json)
        {
            // 创建XDocument的根节点  
            XNamespace S = "http://schemas.xmlsoap.org/soap/envelope/";
            XNamespace ns2 = "http://service.communication.service.dareway.com/";
            XDocument xDoc = new XDocument(new XDeclaration("1.0", "UTF-8", "yes"), new XElement(S + "Envelope", new XElement(S + "Body", new XElement(ns2 + "pipInvokeResponse", new XElement("resultContent", Json)))));
            string xmlString = xDoc.ToString(SaveOptions.None);
            return xmlString;
        }

        /// <summary>
        /// 计算时间戳
        /// </summary>
        /// <param name="dateTime"></param>
        /// <returns></returns>
        public static long ConvertToUnixTimestampMillis(DateTime dateTime)
        {
            // 将DateTime转换为UTC时间，因为Unix时间戳是基于UTC的  
            DateTime utcDateTime = dateTime.ToUniversalTime();

            // 从1970年1月1日午夜（UTC）开始计算毫秒数  
            long unixTimestampMillis = (long)(utcDateTime - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;

            return unixTimestampMillis;
        }
        /// <summary>
        /// 读取配置文件
        /// </summary>
        /// <param name="node">节点</param>
        /// <param name="name">名称</param>
        /// <returns>ini内容</returns>
        public static string ReadInI(string node, string name)
        {
            try
            {
                IniFileHelper Ifh = new IniFileHelper();
                StringBuilder Sb = new StringBuilder(9999);
                Ifh.GetIniString(node, name, "", Sb, Sb.Capacity);
                LogHelper.Info($"[Method.ReadInI]读取节点：{node} 字段：{name} 值：{Sb}");
                return Sb.ToString();
            }
            catch (Exception ex)
            {
                LogHelper.Error($"[Method.Error]ReadInI方法程序异常！节点：" + node + " 字段：" + name + "错误内容：" + ex.Message);
                MessageBox.Show("读取INI配置失败！节点：" + node + " 字段：" + name + "错误内容：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return "";
            }
        }
        /// <summary>
        /// 写入配置文件
        /// </summary>
        /// <param name="node">节点</param>
        /// <param name="name">名称</param>
        /// <param name="text">写入ini内容</param>
        /// <returns>写入是否成功 成功true 失败false</returns>
        public static bool WriteInI(string node, string name, string text)
        {
            try
            {
                IniFileHelper Ifh = new IniFileHelper();
                Ifh.WriteIniString(node, name, text);
                LogHelper.Info($"[Method.WriteInI]写入节点：{node} 字段：{name} 值：{text}");
                return true;
            }
            catch (Exception ex)
            {
                LogHelper.Error($"[Method.Error]WriteInI方法程序异常！节点：" + node + " 字段：" + name + "错误内容：" + ex.Message);
                MessageBox.Show("写入INI配置失败！节点：" + node + " 字段：" + name + "内容：" + text + "错误内容：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return false;
            }
        }
        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="url">下载地址</param>
        /// <param name="sFilePath">保存地址</param>
        /// <returns>下载状态</returns>
        public static bool Downloadfile(string url, string sFilePath)
        {
            try
            {
                WebClient mywebClient = new WebClient();
                mywebClient.DownloadFile(url, sFilePath);
                return true;
            }
            catch 
            {
                return false;
            }
        }
        ///<summary>  
        /// 清空指定的文件夹，但不删除文件夹  
        /// </summary>  
        /// <param name="dir"></param>  
        public static void DeleteFolder(string dir)
        {
            foreach (string d in Directory.GetFileSystemEntries(dir))
            {
                if (System.IO.File.Exists(d))
                {
                    FileInfo fi = new FileInfo(d);
                    if (fi.Attributes.ToString().IndexOf("ReadOnly") != -1)
                        fi.Attributes = FileAttributes.Normal;
                    System.IO.File.Delete(d);//直接删除其中的文件    
                }
                else
                {
                    DirectoryInfo d1 = new DirectoryInfo(d);
                    if (d1.GetFiles().Length != 0)
                    {
                        DeleteFolder(d1.FullName);////递归删除子文件夹  
                    }
                    Directory.Delete(d);
                }
            }
        }


        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static bool DeleteFile(string filePath)
        {
            try
            {
                if (File.Exists(filePath))
                {
                    File.Delete(filePath);
                    return true;
                }
                else
                {
                    return true;
                }
            }
            catch 
            {
                return false;
            }
        }

        /// <summary>
        /// 删除文件夹
        /// </summary>
        /// <param name="path">路径</param>
        public static void DeleteDirectory(string path)
        {
            DirectoryInfo dir = new DirectoryInfo(path);
            if (dir.Exists)
            {
                DirectoryInfo[] childs = dir.GetDirectories();
                foreach (DirectoryInfo child in childs)
                {
                    child.Delete(true);
                }
                dir.Delete(true);
            }
        }
        //获取IP与Mac
        public static void GetIPMac()
        {

            try
            {
                string ip = "";
                string mac = "";
                ManagementClass mc;
                string hostInfo = Dns.GetHostName();
                IPAddress[] addressList = Dns.GetHostEntry(Dns.GetHostName()).AddressList;
                for (int i = 0; i < addressList.Length; i++)
                {
                    ip = addressList[i].ToString();
                }
                //mac地址
                mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {
                    if (mo["IPEnabled"].ToString() == "True")
                    {
                        mac = mo["MacAddress"].ToString();
                    }
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show("获取IP地址或MAC地址失败！错误内容：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        /// <summary>
        /// 获取现在时间戳，毫秒
        /// </summary>
        /// <returns></returns>
        public static string GetMilliTimeStamp()
        {
            return DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString();
        }

        /// <summary>
        /// Base64字符串转文件并保存
        /// </summary>
        /// <param name="base64String">base64字符串</param>
        /// <param name="fileFullPath">保存的文件路径</param>
        /// <param name="fileName">保存的文件名</param>
        /// <returns>是否转换并保存成功</returns>
        public static string Base64StringToFile(out bool state,string base64String, string fileFullPath,string fileName)
        {
            string pdfpath = "";
            try
            {
                if (!Directory.Exists(fileFullPath))
                {
                    Directory.CreateDirectory(fileFullPath);
                }
                string strbase64 = base64String.Trim().Substring(base64String.IndexOf(",") + 1);   //将‘，’以前的多余字符串删除
                MemoryStream stream = new MemoryStream(Convert.FromBase64String(strbase64));
                FileStream fs = new FileStream(fileFullPath + "\\" + fileName, FileMode.OpenOrCreate, FileAccess.Write);
                byte[] b = stream.ToArray();
                fs.Write(b, 0, b.Length);
                fs.Close();
                pdfpath = fileFullPath + "\\" + fileName;
                state = true;
                return pdfpath;

            }
            catch (Exception e)
            {
                pdfpath = $"base64字符串转文件失败！错误内容：{e.Message} 异常来源：{e.StackTrace}";
                state=false;
                return pdfpath;
            }
        }

        /// <summary>
        /// 刷新参数配置
        /// </summary>
        public static void RefreshConfiguration()
        {
            try
            {
                LogHelper.Info($"----------开始刷新/获取参数配置----------");

                SystemInfo.localurl = PublicMethod.ReadInI("SystemInfo", "localurl");
                SystemInfo.localurlpost = int.Parse(PublicMethod.ReadInI("SystemInfo", "localurlpost"));

                LogDeleteSettings.ErrorLogDeleteActive = bool.Parse(PublicMethod.ReadInI("SystemInfo", "ErrorLogDeleteActive"));
                LogDeleteSettings.ErrorLogDeleteDay = int.Parse(PublicMethod.ReadInI("SystemInfo", "ErrorLogDeleteDay"));
                LogDeleteSettings.InfoLogDeleteActive = bool.Parse(PublicMethod.ReadInI("SystemInfo", "InfoLogDeleteActive"));
                LogDeleteSettings.InfoLogDeleteDay = int.Parse(PublicMethod.ReadInI("SystemInfo", "InfoLogDeleteDay"));

                ApiDatainfo.mysqlUrl = PublicMethod.ReadInI("ApiDatainfo", "mysqlUrl");
                ApiDatainfo.mysqlDatabase = PublicMethod.ReadInI("ApiDatainfo", "mysqlDatabase");
                ApiDatainfo.mysqlPost = PublicMethod.ReadInI("ApiDatainfo", "mysqlPost");
                ApiDatainfo.mysqlPwd = PublicMethod.ReadInI("ApiDatainfo", "mysqlPwd");
                ApiDatainfo.mysqlUser = PublicMethod.ReadInI("ApiDatainfo", "mysqlUser");

                FsiEpcTokeninfo.appId = PublicMethod.ReadInI("FsiEpcTokeninfo", "appId");
                FsiEpcTokeninfo.appSecret = PublicMethod.ReadInI("FsiEpcTokeninfo", "appSecret");
                FsiEpcTokeninfo.privateKey = PublicMethod.ReadInI("FsiEpcTokeninfo", "privateKey");
                FsiEpcTokeninfo.publicKey = PublicMethod.ReadInI("FsiEpcTokeninfo", "publicKey");

                FsiDatainfo.Ecccodecardno = PublicMethod.ReadInI("FsiDatainfo", "Ecccodecardno");
                FsiDatainfo.Defautlcardno = PublicMethod.ReadInI("FsiDatainfo", "Defautlcardno");
                FsiDatainfo.JiangsuDefautlcardno = PublicMethod.ReadInI("FsiDatainfo", "JiangsuDefautlcardno");

                FsiDatainfo.stateNeusJiangsuApi = bool.Parse(PublicMethod.ReadInI("FsiDatainfo", "stateNeusJiangsuApi"));
                FsiDatainfo.stateFsiApi = bool.Parse(PublicMethod.ReadInI("FsiDatainfo", "stateFsiApi"));
                FsiDatainfo.stateFsiEpcApi = bool.Parse(PublicMethod.ReadInI("FsiDatainfo", "stateFsiEpcApi"));
                FsiDatainfo.statesignon = bool.Parse(PublicMethod.ReadInI("FsiDatainfo", "statesignon"));
                FsiDatainfo.stateShandongBinzhouApi = bool.Parse(PublicMethod.ReadInI("FsiDatainfo", "stateShandongBinzhouApi"));
                FsiDatainfo.stateShandongDarewayApi = bool.Parse(PublicMethod.ReadInI("FsiDatainfo", "stateShandongDarewayApi"));
                FsiDatainfo.stateShandongJxcApi = bool.Parse(PublicMethod.ReadInI("FsiDatainfo", "stateShandongJxcApi"));
                FsiDatainfo.stateLocalApiInInternal = bool.Parse(PublicMethod.ReadInI("FsiDatainfo", "stateLocalApiInInternal"));

                FsiDatainfo.fund_pay_sumamt = double.Parse(PublicMethod.ReadInI("FsiDatainfo", "fund_pay_sumamt"));
                FsiDatainfo.psn_cash_pay = double.Parse(PublicMethod.ReadInI("FsiDatainfo", "psn_cash_pay"));
                FsiDatainfo.acct_pay = double.Parse(PublicMethod.ReadInI("FsiDatainfo", "acct_pay"));
                FsiDatainfo.clcYearAcctPay = double.Parse(PublicMethod.ReadInI("FsiDatainfo", "clcYearAcctPay"));
                FsiDatainfo.crtYearAcctPay = double.Parse(PublicMethod.ReadInI("FsiDatainfo", "crtYearAcctPay"));
                FsiDatainfo.acct_mulaid_pay = double.Parse(PublicMethod.ReadInI("FsiDatainfo", "acct_mulaid_pay"));

                FsiDatainfo.cvlserv_pay = double.Parse(PublicMethod.ReadInI("FsiDatainfo", "cvlserv_pay"));
                FsiDatainfo.hifdm_pay = double.Parse(PublicMethod.ReadInI("FsiDatainfo", "hifdm_pay"));
                FsiDatainfo.hifmi_pay = double.Parse(PublicMethod.ReadInI("FsiDatainfo", "hifmi_pay"));
                FsiDatainfo.act_pay_dedc = double.Parse(PublicMethod.ReadInI("FsiDatainfo", "act_pay_dedc"));
                FsiDatainfo.hifob_pay = double.Parse(PublicMethod.ReadInI("FsiDatainfo", "hifob_pay"));
                FsiDatainfo.oth_pay = double.Parse(PublicMethod.ReadInI("FsiDatainfo", "oth_pay"));
                FsiDatainfo.hifes_pay = double.Parse(PublicMethod.ReadInI("FsiDatainfo", "hifes_pay"));
                FsiDatainfo.fulamt_ownpay_amt = double.Parse(PublicMethod.ReadInI("FsiDatainfo", "fulamt_ownpay_amt"));
                FsiDatainfo.hosp_part_amt = double.Parse(PublicMethod.ReadInI("FsiDatainfo", "hosp_part_amt"));
                FsiDatainfo.inscp_scp_amt = double.Parse(PublicMethod.ReadInI("FsiDatainfo", "inscp_scp_amt"));
                FsiDatainfo.maf_pay = double.Parse(PublicMethod.ReadInI("FsiDatainfo", "maf_pay"));
                FsiDatainfo.overlmt_selfpay = double.Parse(PublicMethod.ReadInI("FsiDatainfo", "overlmt_selfpay"));
                FsiDatainfo.preselfpay_amt = double.Parse(PublicMethod.ReadInI("FsiDatainfo", "preselfpay_amt"));
                LogHelper.Info($"----------结束刷新/获取参数配置----------");
            }
            catch (Exception ex)
            {
                LogHelper.Error($"[Methond.RefreshConfiguration]参数配置获取失败！异常提示：{ex.Message} 异常来源：{ex.StackTrace}");
                MessageBox.Show($"参数配置获取失败！ 错误内容：{ex.Message}  异常来源：{ex.StackTrace}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
        }
    }
}
